package com.zjh.jdqlib.ui

import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.le.ScanResult
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.RecyclerView
import com.coder.vincent.smart_toast.SmartToast
import com.drake.brv.utils.divider
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.wuhao.jdqlib.databinding.ItemDeviceBleInfoBinding
import com.wuhao.jdqlibnoui.utils.JdqLibUtilNoui
import com.wuhao.jdqlib.utils.throttleClick
import com.wuhao.jdqlibnoui.constants.AppConfig
import com.wuhao.jdqlibnoui.interf.JdqCallBackNoUI
import com.wuhao.jdqlibnoui.interf.JdqCallback
import com.zjh.jdqlib.R
@SuppressLint("MissingPermission")
class NouiActivity : AppCompatActivity() {
    val TAG = "NouiActivity"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_noui)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        initView()
    }
    val jdqLibUtil = JdqLibUtilNoui(this, this@NouiActivity)
    var bleStatus: TextView? = null
    var connectStatus: TextView? = null
    var dataTv: TextView? = null
    var rvBleList: RecyclerView? = null

    // 创建一个ActivityResultLauncher来启动蓝牙开启请求
    private val enableBtLauncher=
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                // 用户同意开启了蓝牙
                //蓝牙列表
                //startActivity(Intent(this@NouiActivity, BleListActivity::class.java))
            } else {
                // 用户拒绝开启蓝牙
                SmartToast.emotion().warning(com.wuhao.jdqlib.R.string.ble_permission_disagree)
            }
        }
    fun initView(){
        bleStatus = findViewById(R.id.ble_status)
        connectStatus = findViewById(R.id.connect_status)
        dataTv = findViewById(R.id.data)
        rvBleList = findViewById(R.id.rv_ble_list)
        findViewById<Button>(R.id.startscan).throttleClick {
            jdqLibUtil.startBleScan()
        }
        findViewById<Button>(R.id.stopscan).throttleClick {
            jdqLibUtil.stopBleScan()
        }
        findViewById<Button>(R.id.disconnect).throttleClick {
            jdqLibUtil.disConnect()
        }
        jdqLibUtil.initBlueNoUI(enableBtLauncher)

        jdqLibUtil.registeJdqCallBackNoUI(object : JdqCallBackNoUI {
            override fun scanResult(code: Int, bleList: ArrayList<ScanResult>) {
                Log.e(TAG,"${code}----${bleList.size}")
                rvBleList?.models = bleList
                bleStatus?.text="${code}----${bleList.size}"
            }

            override fun scanStatus(code: Int) {
                Log.e(TAG,"${code}")
            }
        })

        jdqLibUtil.registerCallBack(object : JdqCallback {
            override fun onBlueConnected() {
                connectStatus?.text = "onBlueConnected"
            }

            override fun onBlueDisconnected() {
                connectStatus?.text = "onBlueDisconnected"
            }

            override fun onDataReceived(data: String) {
                dataTv?.text = "$data"
            }

            override fun onError(error: String) {
                dataTv?.text = "$error"
            }

        })
        initRecyclerView()
    }


    private var deviceList: ArrayList<ScanResult> = arrayListOf()
    private fun initRecyclerView() {
        rvBleList?.linear()?.divider {
            setDivider(1, true)
            setColor(getColor(com.wuhao.jdqlib.R.color.bg_item_img))
        }?.setup {
            addType<ScanResult>(com.wuhao.jdqlib.R.layout.item_device_ble_info)

            onBind {
                val model = getModel<ScanResult>()
                val holder = getBinding<ItemDeviceBleInfoBinding>()
                if (model.device.name == AppConfig.bleName && model.device.address == AppConfig.bleMac) {
                    holder.paired.text = getString(com.wuhao.jdqlib.R.string.before_time_paired)
                } else {
                    holder.paired.text = getString(com.wuhao.jdqlib.R.string.paired)
                }
                holder.name.text = model.device.name
                holder.signalView.setSignalValue(getValueByRssi(model.rssi))
                holder.rssi.text = "${model.rssi}dBm"
                holder.address.text = model.device.address
            }
            onClick(com.wuhao.jdqlib.R.id.rl_item) {
                val model = getModel<ScanResult>()
                jdqLibUtil.connectToBle(model)
            }
        }?.models = deviceList
    }

    /**
     * 转换信号等级
     */
    private fun getValueByRssi(rssi: Int): Int {
        return if (rssi > -60) {
            5
        } else if (rssi > -70) {
            4
        } else if (rssi > -75) {
            3
        } else if (rssi > -80) {
            2
        } else if (rssi > -85) {
            1
        } else {
            0
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        jdqLibUtil.cleanResource()
    }

}